package com.culture.config.common.filter;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.apache.commons.io.IOUtils;

public class FilterRequestWrapper extends HttpServletRequestWrapper {
    private HttpServletRequest request;
    private final Map<String, String> customHeaders = new HashMap<>();
    private final Map<String, String> customParams = new HashMap<>();
    private byte[] body;
    private ServletInputStreamWrapper inputStreamWrapper;
    public FilterRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        this.request = request;
        this.initFilter();
    }

    private void initFilter() throws IOException{
       this.body = IOUtils.toByteArray(this.request.getInputStream());
       this.inputStreamWrapper = new ServletInputStreamWrapper(new ByteArrayInputStream(this.body));
       this.inputStreamWrapper.setInputStream(new ByteArrayInputStream(this.body != null ? this.body : new byte[0]));
    } 
    public byte[] getBody() {
        return this.body;
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        return this.inputStreamWrapper;
    }

    public void putHeader(String key, String value) {
        this.customHeaders.put(key, value);
    }  

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(this.inputStreamWrapper));
    }

    @Override
    public String getHeader(String name) {
        return customHeaders.getOrDefault(name, super.getHeader(name));
    }   

    @Override
    public Enumeration<String> getHeaderNames() {
        Set<String> headerSet = new HashSet<>(customHeaders.keySet());
        Enumeration<String> headerNames = super.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            headerSet.add(headerNames.nextElement());
        }
        return Collections.enumeration(headerSet);
    }

    @Override
    public String getParameter(String name) {
        String[] vals = this.getParameterMap().get(name);
        if (vals != null && vals.length > 0)
            return vals[0];
        else
            return this.customParams.getOrDefault(name, null);
    }
   
    public void setParameter(String name,String value) {
        this.customParams.put(name,value);
    }
}